//
//  UIView+Add.swift
//  ContactPoster
//
//  Created by TSYH on 2023/11/21.
//

import UIKit
import Kingfisher

public extension UIViewController {
    /// topViewController for Window
    static var topViewController: UIViewController? {
        var result = UIScreen.keyWindow?.rootViewController
        while true {
            if let navController = result as? UINavigationController {
                result = navController.visibleViewController
            } else if let tabController = result as? UITabBarController {
                result = tabController.selectedViewController
            } else if let presentController = result?.presentedViewController {
                result = presentController
            } else {
                break
            }
        }
        return result
    }
}

public extension UIView {
    var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = true
        }
        get {
            layer.cornerRadius
        }
    }
    
    var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            layer.borderWidth
        }
    }
    
    var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            if let cgColor = layer.borderColor {
                return UIColor(cgColor: cgColor)
            }
            return nil
        }
    }
    
    func addCorner(radius: CGFloat, color: UIColor, width: CGFloat) {
        layer.cornerRadius = radius
        layer.borderColor = color.cgColor
        layer.borderWidth = width
        layer.masksToBounds = true
    }
    
    // 部分圆角（必须Frame已知）
    func makeCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = path.cgPath
        layer.mask = maskLayer
    }
}

public extension UIImageView {
    func setImage(_ urlString: String?,
                  thumbnail size: CGSize = .zero,
                  placeHolder: String? = nil,
                  cache: ImageCache? = nil,
                  completionHandler: ((UIImage?) -> Void)? = nil) {
        var placeHolderView: ImageLoadPlaceholder?
        if let imageName = placeHolder {
            placeHolderView = ImageLoadPlaceholder(with: imageName)
        }
        setImage(urlString, thumbnailSize: size, placeHolder: placeHolderView, cache: cache, completionHandler: completionHandler)
    }
        
    func setImage(_ urlString: String?,
                  thumbnailSize: CGSize = .zero,
                  thumbnailScale: CGFloat = UIScreen.main.scale,
                  placeHolder: Placeholder? = nil,
                  cache: ImageCache? = nil,
                  completionHandler: ((UIImage?) -> Void)? = nil) {
        self.image = nil
        guard let urlString = urlString,
                let url = URL(string: urlString) else {
            return
        }
        
        var options: KingfisherOptionsInfo?
        if thumbnailSize != .zero {
            let resizeProcessor = ResizingImageProcessor(referenceSize: thumbnailSize.applying(CGAffineTransform(scaleX: thumbnailScale, y: thumbnailScale)), mode: .aspectFill)
            options = [.processor(resizeProcessor), .cacheOriginalImage]
        }
        if let cache = cache {
            options?.append(.targetCache(cache))
        }
        
        kf.setImage(with: url, placeholder: placeHolder, options: options) { result in
            switch result {
            case let .success(imageResult):
                completionHandler?(imageResult.image)
            case let .failure(error):
                completionHandler?(nil)
            }
        }
    }
}

public extension UIButton {
    func setImage(_ urlString: String?,
                  thumbnailSize: CGSize = .zero,
                  thumbnailScale: CGFloat = 1.5,
                  placeHolder: Placeholder? = nil,
                  for state: UIControl.State = .normal,
                  completionHandler: ((UIImage?) -> Void)? = nil) {
        self.setImage(nil, for: state)
        guard let urlString = urlString,
                let url = URL(string: urlString) else {
            return
        }
        
        var options: KingfisherOptionsInfo?
        if thumbnailSize != .zero {
            let resizeProcessor = ResizingImageProcessor(referenceSize: thumbnailSize.applying(CGAffineTransform(scaleX: thumbnailScale, y: thumbnailScale)), mode: .aspectFill)
            options = [.processor(resizeProcessor), .cacheOriginalImage]
        }
        
        kf.setImage(with: url, for: state, options: options) { result in
            switch result {
            case let .success(imageResult):
                completionHandler?(imageResult.image)
            case let .failure(error):
                completionHandler?(nil)
            }
        }
    }
}
